package com.cat.binaryTree;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
 * @create 2025/9/15 19:09
 * @since JDK17
 */

public class Solution43 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;
        }
        TreeNode l = lowestCommonAncestor(root.left, p, q);
        TreeNode r = lowestCommonAncestor(root.right, p, q);
        if (l != null && r != null) {
            return root;
        }
        if (l != null) {
            return l;
        }
        return r;
    }
}
